/*
 * @Author: your name
 * @Date: 2022-03-30 14:19:31
 * @LastEditTime: 2022-04-28 16:04:48
 * @LastEditors: Please set LastEditors
 * @Description: 本地验证策略
 * @FilePath: \blog-api\src\user\entities\local.strategy.ts
 */
// local.strategy.ts
import { isOk } from 'src/utils/bcrypt'
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { HttpException, HttpStatus } from '@nestjs/common';
import { Repository } from 'typeorm';
import { IStrategyOptions, Strategy } from 'passport-local';
import { User } from './user.entity';

export class LocalStorage extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
    ) {

        super({
            usernameField: 'username',
            passwordField: 'password',
        } as IStrategyOptions);
    }

    async validate(username: string, password: string) {
        const user = await this.userRepository
            .createQueryBuilder('user')
            .addSelect('user.password')
            .where('user.user_tel=:username', { username })
            .getOne();

        if (!user) {
            throw new HttpException('用户名不正确！', HttpStatus.BAD_REQUEST);
        }
        // 变更 !isOk(password, user.password) => password != user.password
        if (password != user.password) {
            throw new HttpException('密码错误！', HttpStatus.BAD_REQUEST);
        }
        return user;
    }
}
